package com.walkerma.library;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import android.os.Handler;

public class ThreadReadText extends Thread {
	public final static int MSG_SD_NotReady = 30000;
	public final static int MSG_FileNotFound = 30001;
	public final static int MSG_ReadError = 30002;
	public final static int MSG_ReadOK = 30003;
	
	private Handler mHandler;
	private String fileName;

	public ThreadReadText(Handler mHandler, String fileName) {
		this.mHandler = mHandler;
		this.fileName = fileName;
	}

	public void run(){
		if(FileProcess.isExternalStorageValid() == false) {
			mHandler.obtainMessage(MSG_SD_NotReady, 
					0, 0, null).sendToTarget();
			return;
		}
		File file = new File(fileName);		
		FileInputStream fin;
		try {
			fin = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			mHandler.obtainMessage(MSG_FileNotFound, 
					0, 0, null).sendToTarget();
			return;
		}
		BufferedReader br = new BufferedReader(
				new InputStreamReader(new BufferedInputStream(fin)));
		StringBuffer sb = new StringBuffer(); 
		try{
			while(br.ready()) sb.append((char)(br.read()));
		}catch (IOException e) {
			e.printStackTrace();
			mHandler.obtainMessage(MSG_ReadError, 
					0, 0, null).sendToTarget();
			return;
		}
		try {
			br.close();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		mHandler.obtainMessage(MSG_ReadOK, 
				0, 0, sb.toString()).sendToTarget();
	}
}
